/*client.c*/
#include "pipelib.h"

int main() {
    int server_fifo_fd;
    int client_fifo_fd;
    int res;
    char client_fifo_name[NAME_SIZE];
    message msg;
    char *p;

    // 创建服务器从客户端接收消息的管道文件
    if (mkfifo(SERVER_FIFO_NAME, 0666) == -1) {  // 使用更合理的权限0666
        fprintf(stderr, "Sorry, create server fifo failure!\n");
        return -1;
    }

    server_fifo_fd = open(SERVER_FIFO_NAME, O_RDONLY);  // 打开管道
    if (server_fifo_fd == -1) {
        fprintf(stderr, "Sorry, server fifo open failure!\n");
        return -1;
    }

    sleep(5);
    while ((res = read(server_fifo_fd, &msg, sizeof(msg))) > 0) {  // 从服务器管道读取数据
        p = msg.data;
        while (*p) {
            *p = toupper(*p);  // 转换为大写字母
            p++;
        }

        // 构造客户端FIFO名称
        snprintf(client_fifo_name, NAME_SIZE, "%s_%d", CLIENT_FIFO_NAME, msg.client_pid);
        
        client_fifo_fd = open(client_fifo_name, O_WRONLY);  // 打开客户端的管道
        if (client_fifo_fd == -1) {
            fprintf(stderr, "Sorry, client fifo open failure!\n");
            close(server_fifo_fd);
            return -1;
        }

        write(client_fifo_fd, &msg, sizeof(msg));  // 将消息通过客户端管道发送
        close(client_fifo_fd);
    }

    close(server_fifo_fd);
    // 客户端不应删除服务器FIFO，此处删除逻辑错误，移除unlink(SERVER_FIFO_NAME);
    return EXIT_SUCCESS;
}
